import { defineComponent, onMounted, reactive, ref } from 'vue';
import { ActionSheet } from 'vant';
import * as qs from 'querystring';
import Cookies from 'js-cookie';
import { loginFeishu, fetchCompanys, chooseCompany } from '@/services';
import router from '@/router';

export default defineComponent({
  setup() {
    const { code, app_id, query, companyId, redirctPath } = qs.parse(window.location.href.split('?')[1]);

    const actions = reactive<any>({
      companies: [],
    });

    const show = ref<boolean>(false);

    onMounted(() => {
      login();
    });

    const login = async () => {
      const res: any =
        (await loginFeishu({
          code,
          externalAppId: app_id,
          serviceId: 6,
        })) || {};
      Cookies.set('sid', res.sid);
      Cookies.set('token', res.token);
      Cookies.set('userInfo', JSON.stringify({ ...res.userDto }));
      if (query && companyId) {
        setCpy(companyId as string).then(() => {
          router.replace(redirctPath as string);
        });
      } else {
        getCompany();
      }
    };

    // 获取企业
    const getCompany = async () => {
      const res: any = (await fetchCompanys({ types: ['SERVER'] })) || [];
      if (res.length === 1) {
        return setCpy(res[0].id);
      }
      // 因为把卖家转换成企业了，会导致每个bd有大量的企业，不方便查看，暂时只显示带有“标果”字样的企业
      actions.companies = res.filter((item: any) => item.name && item.name.includes('标果'));
      show.value = true;
    };

    const setCpy = (companyId: number | string) => {
      return chooseCompany({ companyId }).then(({ sid, token, userName, userId }: any) => {
        Cookies.set('sid', sid);
        Cookies.set('token', token);
        const userDto = Cookies.get('userInfo');
        Cookies.set('userInfo', JSON.stringify({ ...JSON.parse(userDto), userId, userName }));
        router.replace('/home');
      });
    };

    const onSelect = (item: any) => {
      setCpy(item.id);
    };

    return () => {
      return (
        <ActionSheet
          close-on-click-overlay={false}
          v-model={[show.value, 'show']}
          actions={actions.companies}
          onSelect={onSelect}
        />
      );
    };
  },
});
